import { useRef, useState } from "react";
import { message } from "szcd";
// import inherits from "inherits";
import flowableDescriptor from '@/components/ProcessDesigner/bpmn/descriptor/flowable.json';
import Viewer from "bpmn-js/lib/Viewer";
import ZoomScrollModule from "diagram-js/lib/navigation/zoomscroll";
import MoveCanvasModule from "diagram-js/lib/navigation/movecanvas";
import type Canvas from "diagram-js/lib/core/Canvas";
import { type Element } from "bpmn-js/lib/model/Types";
import type ElementRegistry from "diagram-js/lib/core/ElementRegistry";
// import useFullscreen from "@/hooks/useFullscreeen";

const useFlowView = () => {
  // const [, { enterFullscreen }] = useFullscreen(() => el.current);
  const [xml, setXml] = useState("");
  const [processNodeInfo, setProcessNodeInfo] = useState<any>({});
  const viewerRef = useRef<Viewer | null>(null);

  const initView = async ({ el, xml }: { el: HTMLDivElement, xml: string }) => {
    if (viewerRef.current) viewerRef.current.destroy();
    viewerRef.current = new Viewer({
      container: el,
      additionalModules: [
        ZoomScrollModule,
        MoveCanvasModule,
      ],
      moddleExtensions: {
        flowable: flowableDescriptor
      }
    });
    await loadXml(xml);
    window.setTimeout(() => {
      addCustomShape();
    }, 100);
  };

  const getViewer = () => {
    if (!viewerRef.current) {
      throw new Error('Viewer is not initialized');
    }
    return viewerRef.current;
  };
  // 设置高亮颜色的
  const fillColor = (nodeData: any[]) => {

    const canvas = getViewer().get<Canvas>('canvas');

    if (!getViewer().getDefinitions()?.rootElements?.[0]) {
      return;
    }

    getViewer().getDefinitions().rootElements[0].flowElements.forEach((n: Element) => {
      const completeTask = nodeData.find(m => m.key === n.id);
      const todoTask = nodeData.find(m => !m.completed);
      const endTask = nodeData[nodeData.length - 1];
      if (n.$type === 'bpmn:UserTask') {
        if (completeTask) {
          canvas.addMarker(n.id, completeTask.completed ? 'highlight' : 'highlight-todo');
          n.outgoing?.forEach(nn => {
            const targetTask = nodeData.find(m => m.key === nn.targetRef.id);
            if (targetTask) {
              if (todoTask && completeTask.key === todoTask.key && !todoTask.completed) {
                canvas.addMarker(nn.id, todoTask.completed ? 'highlight' : 'highlight-todo');
                canvas.addMarker(nn.targetRef.id, todoTask.completed ? 'highlight' : 'highlight-todo');
              } else {
                canvas.addMarker(nn.id, targetTask.completed ? 'highlight' : 'highlight-todo');
                canvas.addMarker(nn.targetRef.id, targetTask.completed ? 'highlight' : 'highlight-todo');
              }
            }
          });
        }
      }
      // 排他网关
      else if (n.$type === 'bpmn:ExclusiveGateway') {
        if (completeTask) {
          canvas.addMarker(n.id, completeTask.completed ? 'highlight' : 'highlight-todo');
          n.outgoing?.forEach(nn => {
            const targetTask = nodeData.find(m => m.key === nn.targetRef.id);
            if (targetTask) {

              canvas.addMarker(nn.id, targetTask.completed ? 'highlight' : 'highlight-todo');
              canvas.addMarker(nn.targetRef.id, targetTask.completed ? 'highlight' : 'highlight-todo');
            }

          });
        }

      }
      // 并行网关
      else if (n.$type === 'bpmn:ParallelGateway') {
        if (completeTask) {
          canvas.addMarker(n.id, completeTask.completed ? 'highlight' : 'highlight-todo');
          n.outgoing?.forEach(nn => {
            const targetTask = nodeData.find(m => m.key === nn.targetRef.id);
            if (targetTask) {
              canvas.addMarker(nn.id, targetTask.completed ? 'highlight' : 'highlight-todo');
              canvas.addMarker(nn.targetRef.id, targetTask.completed ? 'highlight' : 'highlight-todo');
            }
          });
        }
      }
      else if (n.$type === 'bpmn:StartEvent') {
        n.outgoing.forEach(nn => {
          const completeTask = nodeData.find(m => m.key === nn.targetRef.id);
          if (completeTask) {
            canvas.addMarker(nn.id, 'highlight');
            canvas.addMarker(n.id, 'highlight');

          }
        });
      }
      else if (n.$type === 'bpmn:EndEvent') {
        if (endTask && endTask.key === n.id && endTask.completed) {
          canvas.addMarker(n.id, 'highlight');

        }
      }
    });
  };

  const addCustomShape = () => {
    const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
    defs.innerHTML = `
      <marker id="sequenceflow-end-white-success" viewBox="0 0 20 20" refX="11" refY="10" markerWidth="10" markerHeight="10" orient="auto">
        <path class="success-arrow" d="M 1 5 L 11 10 L 1 15 Z" style="stroke-width: 1px; stroke-linecap: round; stroke-dasharray: 10000, 1;" />
      </marker>
      <marker id="conditional-flow-marker-white-success" viewBox="0 0 20 20" refX="-1" refY="10" markerWidth="10" markerHeight="10" orient="auto">
        <path class="success-conditional" d="M 0 10 L 8 6 L 16 10 L 8 14 Z" style="stroke-width: 1px; stroke-linecap: round; stroke-dasharray: 10000, 1;" />
      </marker>
        <marker id="sequenceflow-end-white-fail" viewBox="0 0 20 20" refX="11" refY="10" markerWidth="10" markerHeight="10" orient="auto">
        <path class="fail-arrow" d="M 1 5 L 11 10 L 1 15 Z" style="stroke-width: 1px; stroke-linecap: round; stroke-dasharray: 10000, 1;" />
      </marker>
      <marker id="conditional-flow-marker-white-fail" viewBox="0 0 20 20" refX="-1" refY="10" markerWidth="10" markerHeight="10" orient="auto">
        <path class="fail-conditional" d="M 0 10 L 8 6 L 16 10 L 8 14 Z" style="stroke-width: 1px; stroke-linecap: round; stroke-dasharray: 10000, 1;" />
      </marker>
      `;
    addDefs(defs);
  };

  // 添加自定义箭头
  const addDefs = (customSuccessDefs: SVGDefsElement) => {
    const canvas = getViewer().get<any>('canvas');
    const svg = canvas._svg as SVGElement;
    // const customSuccessDefs = this.$refs.customSuccessDefs;
    // const customFailDefs = this.$refs.customFailDefs;
    svg.appendChild(customSuccessDefs);
    // svg.appendChild(customFailDefs);
  };

  // 设置流程图元素状态
  const setProcessStatus = (processNodeInfo: { finishedTaskSet: any; rejectedTaskSet: any; unfinishedTaskSet: any; finishedSequenceFlowSet: any; }) => {
    const canvas = getViewer().get<Canvas>('canvas');
    const elementRegistry = getViewer().get<ElementRegistry>('elementRegistry');

    if (!getViewer().getDefinitions()?.rootElements?.[0]) {
      return;
    }

    const { finishedTaskSet, rejectedTaskSet, unfinishedTaskSet, finishedSequenceFlowSet } = processNodeInfo;
    if (Array.isArray(finishedSequenceFlowSet)) {
      finishedSequenceFlowSet.forEach(item => {
        if (item != null) {
          canvas.addMarker(item, 'success');
          const element = elementRegistry.get(item);
          if (element) {
            const conditionExpression = element.businessObject.conditionExpression;
            if (conditionExpression) {
              canvas.addMarker(item, 'condition-expression');
            }
          }
        }
      });
    }
    if (Array.isArray(finishedTaskSet)) {
      finishedTaskSet.forEach(item => { canvas.addMarker(item, 'success'); });
    }
    if (Array.isArray(unfinishedTaskSet)) {
      unfinishedTaskSet.forEach(item => { canvas.addMarker(item, 'primary'); });
    }
    if (Array.isArray(rejectedTaskSet)) {
      rejectedTaskSet.forEach(item => {
        if (item != null) {
          const element = elementRegistry.get(item);
          if (element) {
            if (element.type.includes('Task')) {
              canvas.addMarker(item, 'danger');
            } else {
              canvas.addMarker(item, 'warning');
            }
          }
        }
      });
    }
  };

  const loadXml = async (xml: string) => {
    if (xml) {
      try {
        await getViewer().importXML(xml);
      } catch (e) {
        // console.log(e);
        message.error('流程图加载失败');
      }
    }
  };

  // const zoomRef = useRef(1);
  const zoomViewport = (zoomIn: boolean) => {
    if (getViewer()) {
      const canvas = getViewer().get<Canvas>("canvas");
      const zoomLevel = canvas.zoom();
      const newZoomLevel = zoomLevel + (zoomIn ? 0.1 : -0.1);
      canvas.zoom(newZoomLevel, { x: 0, y: 0 });
    }

    //   放大缩小
    //   zoomViewport(zoomIn = true) {
    //     this.zoom = viewer.get('canvas').zoom()
    //     this.zoom += (zoomIn ? 0.1 : -0.1)
    //     if(this.zoom >= 0.2) viewer.get('canvas').zoom(this.zoom)
    //   },
  };

  // 让图能自适应屏幕
  const fitViewport = () => {
    getViewer().get<Canvas>('canvas').zoom("fit-viewport");
  };

  return {
    initView,
    getViewer,
    fillColor,
    loadXml,
    zoomViewport,
    fitViewport,
    xml,
    setXml,
    setProcessStatus,
    addDefs,
    processNodeInfo,
    setProcessNodeInfo
  };
};

export type IFlowView = ReturnType<typeof useFlowView>;
export default useFlowView;